package com.clinic.web.servlets;

import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.clinic.web.util.Util;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Servlet implementation class Signup
 */
@WebServlet("/Signup")
public class Signup extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Signup() {
		super();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("Enter - doPost in Signup Servlet");
		String first_name = request.getParameter("first_name");
		String last_name = request.getParameter("last_name");
		String email_address = request.getParameter("email_address");
		String passwrd = request.getParameter("passwrd");

		// create json object.
		ObjectMapper mapper = new ObjectMapper();
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("first_name", first_name);
		map.put("last_name", last_name);
		map.put("email_address", email_address);
		map.put("passwrd", passwrd);
		map.put("token", Util.generate_token().toString());
		String jsonfile = mapper.writeValueAsString(map);
		
		// call post method with json format.
		ResourceBundle server = ResourceBundle.getBundle("com/clinic/web/prop/clinicServices", Locale.getDefault());
		String result = Util.POST_Method(server.getString("serverURL") + "patientservices/newpatient", jsonfile);

		if (result.startsWith("Valid")) {
			request.setAttribute("msg", "Activation message sent to your <b>email</b>");
			String[] ar = result.split("&"); // Valid & Token
			String token = ar[1];
			System.out.println("Token = " + token);
			
			// send mail to the creator.
			try {
				Util.sendmailbytemplate(email_address, "You are almost there, verify your email with ***", "signup.ftl", map);
			} catch(Exception ex){
				ex.printStackTrace();
			}
			
		} else if(result.equals("Found")){
			request.setAttribute("msg", "<b>This email used before</b>");
		} else {
			request.setAttribute("msg","Error, please try again later" );
		}
		System.out.println("Exit - doPost in Signup Servlet");
		RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/signup.jsp");
		dispatcher.forward(request, response);
	}
}